import type { Page } from '#/types';
import { requestClient } from '#/api/request';

export namespace LowcodeGroovyApi {
  /** Groovy脚本配置 */
  export interface GroovyScript {
    id?: number;
    scriptName: string;
    displayName: string;
    scriptContent: string;
    description?: string;
    status: number;
    version: number;
    active?: boolean;
    category?: string;
    executeCount?: number;
    lastExecuteTime?: string;
    sort?: number;
    createTime?: string;
    updateTime?: string;
  }

  /** 脚本执行结果 */
  export interface ScriptExecuteResult {
    success: boolean;
    result?: any;
    error?: string;
    executeTime: number;
    logs?: string[];
  }

  /** 脚本缓存信息 */
  export interface ScriptCacheInfo {
    name: string;
    version: number;
    hitCount: number;
    missCount: number;
    loadTime: string;
    expireTime?: string;
    size: number;
  }

  /** 脚本版本历史 */
  export interface ScriptVersion {
    id: number;
    scriptId: number;
    version: number;
    script: string;
    changeDescription?: string;
    createTime: string;
    createBy: string;
  }
}

/** 获取Groovy脚本分页列表 */
export function getGroovyScriptPage(params: any) {
  return requestClient.get<Page<LowcodeGroovyApi.GroovyScript>>('/lowcode/groovy/script/page', {
    params,
  });
}

/** 获取Groovy脚本详情 */
export function getGroovyScript(id: number) {
  return requestClient.get<LowcodeGroovyApi.GroovyScript>(`/lowcode/groovy/script/get`, {
    params: { id },
  });
}

/** 新增Groovy脚本 */
export function createGroovyScript(data: LowcodeGroovyApi.GroovyScript) {
  return requestClient.post('/lowcode/groovy/script/create', data);
}

/** 修改Groovy脚本 */
export function updateGroovyScript(data: LowcodeGroovyApi.GroovyScript) {
  return requestClient.put('/lowcode/groovy/script/update', data);
}

/** 删除Groovy脚本 */
export function deleteGroovyScript(id: number) {
  return requestClient.delete(`/lowcode/groovy/script/delete`, {
    params: { id },
  });
}

/** 执行Groovy脚本 */
export function executeGroovyScript(id: number, params?: any) {
  // 验证参数
  if (!id || id <= 0) {
    return Promise.reject(new Error('脚本ID无效'));
  }

  // 验证执行参数
  if (params && typeof params === 'string') {
    try {
      JSON.parse(params);
    } catch {
      return Promise.reject(new Error('执行参数格式错误，必须是有效的JSON格式'));
    }
  }

  return requestClient.post<LowcodeGroovyApi.ScriptExecuteResult>('/lowcode/groovy/script/execute', {
    id,
    params,
  });
}

/** 直接执行Groovy代码（用于测试） */
export function executeGroovyCode(script: string, params?: any) {
  // 安全检查：禁止危险操作
  const dangerousPatterns = [
    /System\./,
    /Runtime\./,
    /Process/,
    /File\(/,
    /Class\.forName/,
    /\.getClass\(\)/,
    /exec\(/,
    /eval\(/,
    /import\s+java\.lang\.Runtime/,
    /import\s+java\.io/,
    /import\s+java\.nio/,
    /import\s+java\.net/,
    /import\s+groovy\.util\.Eval/,
  ];

  for (const pattern of dangerousPatterns) {
    if (pattern.test(script)) {
      return Promise.reject(new Error(`脚本包含危险操作，已被阻止执行`));
    }
  }

  // 限制脚本长度
  if (script.length > 10000) {
    return Promise.reject(new Error('脚本内容过长，请控制在10000字符以内'));
  }

  return requestClient.post<LowcodeGroovyApi.ScriptExecuteResult>('/lowcode/groovy/script/execute-code', {
    scriptContent: script,
    parameters: params,
  });
}

/** 获取脚本缓存信息 */
export function getScriptCacheInfo() {
  return requestClient.get<LowcodeGroovyApi.ScriptCacheInfo[]>('/lowcode/groovy/script/cache-info');
}

/** 清除脚本缓存 */
export function clearScriptCache(name?: string) {
  return requestClient.post('/lowcode/groovy/script/clear-cache', {
    name,
  });
}

/** 预热脚本缓存 */
export function preloadScriptCache() {
  return requestClient.post('/lowcode/groovy/script/preload-cache');
}

/** 获取脚本版本历史 */
export function getScriptVersionHistory(scriptId: number) {
  return requestClient.get<LowcodeGroovyApi.ScriptVersion[]>('/lowcode/groovy/script/version-history', {
    params: { scriptId },
  });
}

/** 回滚到指定版本 */
export function rollbackScriptVersion(scriptId: number, version: number) {
  return requestClient.post('/lowcode/groovy/script/rollback', {
    scriptId,
    version,
  });
}

/** 切换脚本状态 */
export function updateScriptStatus(id: number, status: number) {
  return requestClient.put('/lowcode/groovy/script/update-status', {
    id,
    status,
  });
}

/** 获取脚本分类列表 */
export function getScriptCategories() {
  return requestClient.get<string[]>('/lowcode/groovy/script/categories');
}